# -*- coding:utf-8 -*-
"""Created By Corvo"""

import weakref

import mod.client.extraClientApi as clientApi

from base import LogicBlockClientBase
from .....common.system import *


class LogicRpcDoubleBlockClient(LogicBlockClientBase):
    """
    逻辑双端方块客户端\n
    - 需要定义数据键和绑定ui
    """
    __mVersion__ = 2

    def __init__(self, name, dim, pos):
        super(LogicRpcDoubleBlockClient, self).__init__(name, dim, pos)
        self.rpc = None
        self.block_ui = None

    def OnDestroy(self):
        if self.rpc:
            self.rpc.Discard()
            del self.rpc
        del self.block_ui
        super(LogicRpcDoubleBlockClient, self).OnDestroy()

    # -----------------------------------------------------------------------------------

    @property
    def server(self):
        return self.rpc

    @property
    def ui(self):
        return self.block_ui

    def server_recall(self, recall):
        return self.rpc(recall)

    # -----------------------------------------------------------------------------------

    def OnFinishedLoadData(self):
        super(LogicRpcDoubleBlockClient, self).OnFinishedLoadData()
        if self._block_bind_ui:
            self.NotifyToServer(ClientEvent.OnUIOpenBlockScreenEvent, {
                "playerId": self.local_id,
                "name": self.block_name,
                "dim": self.block_dim,
                "pos": self.block_pos,
            })

    def OnUISetExit(self):
        super(LogicRpcDoubleBlockClient, self).OnUISetExit()
        # 关闭界面
        clientApi.PopScreen()
        # 服务端删除玩家
        self.server.DelPlayer(self.local_id)
        # 关闭逻辑方块
        self.ShuntDownBlock()

    def OnUIFinishedCreate(self, data):
        # 服务端同步加载
        self.server.OnPlayerFinishedCreateUI(self.local_id)

    def OnServerBlockAddPlayer(self, rpc, data):
        self.rpc = self.ModuleSystem.CreateRpcModule(self, rpc)

        def recall(ui):
            self.block_ui = weakref.proxy(ui)
            # 界面完成创建
            self.OnUIFinishedCreate(data)

        # 开启绑定界面
        self.PushCreateUI(self._block_bind_ui, {"logic_block": self, "recall": recall})
